Ext.define('Seq.app.BaseController', {
    extend: 'Ext.app.ViewController',

    getViewport() {
        return Ext.getApplication().getMainView();
    },

    getViewportModel() {
        return this.getViewport().getViewModel();
    },

    getViewportCtrl() {
        return this.getViewport().getController();
    },

    getUser() {
        return this.getViewportModel().get('user');
    },

    getOrg() {
        var me = this;
        return me.getViewModel().get('org') || me.getUser().org;
    },

    getCr() {
        var vm = this.getViewModel();
        return vm.get('record') || vm.data.record;
    },

    redirect(url, params) {
        this.getViewport().getController().fireEvent('redirect', url, params);
    },

    // 从ViewModel中读取，指定名称param的参数；如果params不存在，就加入
    applyIf(params, vm, p) {
        let v = vm.get(p);
        if (!(Ext.isEmpty(v) || (p in params))) {
            params[p] = v;
        }
        return params;
    },

    appliesIf(params, vm, array) {
        let me = this;
        if (Ext.isEmpty(params)) {
            params = {};
        }
        Ext.Array.each(array, function (p) {
            me.applyIf(params, vm, p);
        });
        return me.clean(params);
    },
    // 删除为空的参数，不向后台传递
    clean(params) {
        for (let p in params) {
            var val = params[p];
            if (Ext.isArray(val)) { // 对象数组
                val = Ext.Array.clone(val);
                var i, len = val.length;
                for (i = 0; i < len; i++) {
                    if (Ext.isObject(val[i])) {
                        val[i] = val[i].id;
                    }
                }
                params[p] = val;
            } else if (Ext.isObject(val)) { // 如果是对象，优先取id属性(ComboBox)，如果没有再去第一个值(RadioGroup)
                val = val.id || val[Ext.Object.getKeys(val)[0]];
                params[p] = val;
            }
            if (Ext.isEmpty(val)) { // || (-1 == val)) {
                delete params[p];
            }
        }
        return params;
    },

    getExtraParams: function (params) {
        let me = this, record = me.getCr();
        params = params ? params : {};
        if (record) {
            if (!Ext.isEmpty(record.data.id)) {
                params.id = params.id || record.data.id;
            }
            if (!Ext.isEmpty(record.data.level)) {
                params.level = params.level || record.data.level;
            }
        }
        return params;
    },

    /**
     * 加载stores, store可以是string或者object，例如：{name : 'abc', click : true}、{name :
     * 'abc', once : true} once表示只加载一次，click表示点击刷新按钮是，需要重新加载
     *
     */
    loadStores(stores, params, opts) {
        let me = this, vm = me.getViewModel();
        for (let e of stores) {
            let store;
            if (Ext.isObject(e)) {
                store = vm.get(e.name);
                if ((e.once && store.isLoaded())
                    || (e.click && opts && !opts.click && store
                        .isLoaded())) {
                    continue;
                }
            } else {
                store = vm.get(e);
            }
            store.getProxy().extraParams = me.getExtraParams(params);
            store.reload();
        }
    },

    onParamKeyPress(cmp, e, eOpts) {
        if (e.RETURN == e.keyCode) {
            this.onRefreshClick();
        }
    },

    onParamsChange(cmp, newValue, oldValue, eOpts) {
        let me = this, view = me.getView();
        if (!view.isVisible() || !cmp.isVisible()) {
            return;
        }
        if (cmp.isXType('datefield') && !Ext.isDate(newValue)) { // 无效的日期
            return;
        }
        // 增加!Ext.isEmpty(oldValue)判断，页面初始化时多次加载
        if (!Ext.isEmpty(newValue) && !Ext.isEmpty(oldValue) && (newValue !== oldValue)) {
            let params = {};
            params[cmp.getBind().value.stub.name] = newValue;
            view.fireEvent('refreshdata', view, me.getCr(), params, {});
        }
    },

    onRefreshClick(btn) {
        let me = this, view = me.getView();
        view.fireEvent('refreshdata', view, me.getCr(), null, {
            click: true,
            btn: btn
        });
    },

    onReplyClick(btn) {
        window.history.back(-1);
    },

    onBeforeDocumentSave(view) {
        view.mask('正在准备导出数据，请稍后......');
    },

    onDocumentSave(view) {
        view.unmask();
    },

    onDocumentExportError: function (error) {
        Ext.Msg.alert('错误', typeof error === 'string' ? error : '位置错误');
    },

    exportTable(table, filename, title) {
        table.saveDocumentAs({
            type: 'excel07',
            title: title || '',
            author: 'SEQDATA',
            charset: 'GB2312',
            fileName: filename + '.xlsx',
            ext: 'xlsx',
            showSummary: false
        }).then(null, this.onError);
    },

    applyData(datas, mask, url, fnSuccess, options) {
        if (datas.length <= 0) {
            fnSuccess && Ext.callback(fnSuccess);
        } else {
            this.applyDataPermitNull(datas, mask, url, fnSuccess, options);
        }
    },

    /** 允许空值保存，主要用于批量保存的功能 */
    applyDataPermitNull(datas, mask, url, fnSuccess, options) {
        options = options || {};
        Ext.applyIf(options, {
            mask: mask,
            method: 'PUT',
            url: url,
            jsonData: Ext.encode(datas),
            fnSuccess: fnSuccess
        });
        Seq.Ajax.request(options);
    },

    applyStore(store, mask, url, fnSuccess, options) {
        var datas = [];
        Ext.each(store.getModifiedRecords(), function (record) {
            if (record) {
                datas.push(record.data);
            }
        });
        this.applyData(datas, mask, url, fnSuccess, options);
    },

    /** 合并记录到store中 */
    merge(store, record) {
        var id = store.model.idProperty, result = store.find(id, record.data[id], 0, false, true, true);
        if (-1 < result) { // 合并属性
            result = store.getAt(result);
            Ext.apply(result.data, record.data);
            result.commit();
        } else { // 新建记录
            if ('Ext.data.TreeStore' == store.$className) {
                record.parentNode.insertChild(0, record);
            } else {
                result = store.insert(0, record.data)[0];
            }
        }
        return result;
    },

    merges(store, records) {
        let me = this;
        for (let record of records) {
            me.merge(store, record);
        }
    },

    contains(visibles, items) { // 支持单个对象
        if (!visibles) {
            return true;
        }
        if (!Ext.isArray(visibles)) {
            visibles = [visibles];
        }
        if (!Ext.isArray(items)) {
            items = [items];
        }
        var visible;
        for (var i in items) {
            for (var j in visibles) {
                visible = visibles[j];
                if (items[i] === (Ext.isObject(visible)
                    ? visibles[j].name
                    : visible)) {
                    return true;
                }
            }
        }
        return false;
    }

});